import req from './req'

export function treeReplace(
  tree: any,
  replace: any = {},
  { addPids = false, pids = [], treeMap = {}, level = 1 } = {}
) {
  return tree.map((item: any) => {
    for (const key in replace) {
      item[key] = item[replace[key]]
    }
    if (addPids) {
      item.pids = pids
    }
    treeMap[item.key] = item
    item.level = level
    if (item.children) {
      item.children = treeReplace(item.children, replace, {
        addPids,
        pids: pids.concat(item['key']),
        level: level + 1,
        treeMap
      })
    }
    return item
  })
}
export function array2Tree(
  list: any = [],
  pid = null,
  { replace = {}, pids = [], treeMap = {}, level = 1 } = {}
) {
  return (
    list
      // @ts-ignore
      .filter((item) => item[replace.pid || 'pid'] == pid)
      .map((item) => {
        for (const key in replace) {
          item[key] = item[replace[key]]
        }
        console.log(item)
        item.level = level
        item.pids = pids
        treeMap[item.key] = item

        const children = array2Tree(list, item.key, {
          replace,
          pids: pids.concat(item['key']),
          treeMap,
          level: level + 1
        })
        if (children.length > 0) {
          item.children = children
        }
        return item
      })
  )
}
export function filterTree(tree: any, searchValue: any) {
  return tree
    .map((node: any) => {
      const newNode = { ...node }
      newNode.children = node.children ? filterTree(node.children, searchValue) : []
      if (newNode.title.includes(searchValue) || newNode.children.length) {
        return newNode
      }
      return null
    })
    .filter((node: any) => node !== null)
}

export function compareFields(
  id: string,
  oldObj: Record<string, any>,
  newObj: Record<string, any>,
  fieldMap: Record<string, string>
) {
  const strs: {
    entityId: string
    operation: string
    newValue: any
    oldValue: any
    fieldName: string
  }[] = []
  for (const key in fieldMap) {
    if (oldObj[key] !== newObj[key]) {
      strs.push({
        entityId: id,
        operation: '更新',
        oldValue: oldObj[key],
        newValue: newObj[key],
        fieldName: fieldMap[key]
      })
    }
  }
  return strs
}

export function reqCompareLog({
  id,
  oldVal,
  newVal,
  fieldMap
}: {
  id: string
  oldVal: Record<string, any>
  newVal: Record<string, any>
  fieldMap: Record<string, string>
}) {
  const operation = compareFields(id, oldVal, newVal, fieldMap)
  if (operation.length > 0) {
    req.log(operation)
  }
}
